using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using UnityEditor;
using UnityEngine;
using UnityEngine.Rendering;

namespace Mars.ShaderAnalysis
{
    public class ExtendFrameDebuggerEditorWindow : EditorWindow
    {
        [MenuItem("Mars/Shader分析/拓展FrameDebugger", false, 600)]
        public static void OpenWindow()
        {
            ExtendFrameDebuggerEditorWindow editorWindow = GetWindow<ExtendFrameDebuggerEditorWindow>(false, "拓展FrameDebugger", true);
            editorWindow.minSize = new Vector2(WINDOW_MIN_WIDTH, WINDOW_MIN_HEIGHT);
        }
        
        private const float WINDOW_MIN_WIDTH = 750f;
        private const float WINDOW_MIN_HEIGHT = 750f;
        private const float SPACE_SIZE = 5f;
        private const float BUTTON_SIZE = 65f;

        private EditorWindow frameDebuggerWindow;
        private Type FrameDebuggerWindow;
        private Type FrameDebuggerUtility;
        private Type FrameDebuggerEventDetailsView;
        private MethodInfo ChangeFrameEventLimit;
        private MethodInfo RepaintOnLimitChange;
        private MethodInfo GetFrameEventData;
        private MethodInfo SetRenderTargetDisplayOptions;
        private PropertyInfo limit;
        private FieldInfo m_EventDetailsView;

        //Task不能写入Dictionary，只能先用list获取数据
        private Dictionary<Shader, FrameDebuggerEventDataGroup> eventDataDic = new Dictionary<Shader, FrameDebuggerEventDataGroup>();
        private FrameDebuggerEventDataList clearEventDataList = new FrameDebuggerEventDataList();
        private FrameDebuggerEventRtGroup rtGroup = new FrameDebuggerEventRtGroup();

        private Vector2 scrollPosition = Vector2.zero;
        private int toolbarIndex = 0;

        private void OnEnable()
        {
            EditorApplication.update += EditorUpdate;
        }

        private void OnDisable()
        {
            EditorApplication.update -= EditorUpdate;
        }

        private void OnGUI()
        {
            if (FrameDebuggerWindow == null)
            {
                Assembly assembly = Assembly.Load("UnityEditor.CoreModule");
                FrameDebuggerWindow = assembly.GetType("UnityEditor.FrameDebuggerWindow");
                FrameDebuggerUtility = assembly.GetType("UnityEditorInternal.FrameDebuggerInternal.FrameDebuggerUtility");
                ChangeFrameEventLimit = FrameDebuggerWindow.GetMethod("ChangeFrameEventLimit", BindingFlags.Instance | BindingFlags.NonPublic, null, new Type[] { typeof(Int32) }, null);
                RepaintOnLimitChange = FrameDebuggerWindow.GetMethod("RepaintOnLimitChange", BindingFlags.Instance | BindingFlags.NonPublic);
                GetFrameEventData = FrameDebuggerUtility.GetMethod("GetFrameEventData", BindingFlags.Static | BindingFlags.Public);
                SetRenderTargetDisplayOptions = FrameDebuggerUtility.GetMethod("SetRenderTargetDisplayOptions", BindingFlags.Static | BindingFlags.Public);
                limit = FrameDebuggerUtility.GetProperty("limit", BindingFlags.Static | BindingFlags.Public);
                FrameDebuggerEventDetailsView = assembly.GetType("UnityEditorInternal.FrameDebuggerInternal.FrameDebuggerEventDetailsView");
                m_EventDetailsView = FrameDebuggerWindow.GetField("m_EventDetailsView", BindingFlags.Instance | BindingFlags.NonPublic);
            }

            if (frameDebuggerWindow == null)
            {
                MethodInfo OpenWindow = FrameDebuggerWindow.GetMethod("OpenWindow", BindingFlags.Static | BindingFlags.Public);
                frameDebuggerWindow = OpenWindow.Invoke(null, null) as EditorWindow;
            }

            using (new EditorGUILayoutUtility.VerticalScopeWithSpace(SPACE_SIZE + 3, SPACE_SIZE, SPACE_SIZE + 3, SPACE_SIZE))
            {
                using (new EditorGUILayout.VerticalScope("FrameBox"))
                {
                    toolbarIndex = GUILayout.Toolbar(toolbarIndex, new string[]
                    {
                        "Shader变体",
                        "RT切换带宽"
                    }, GUILayout.Height(30f));

                    GUILayout.Space(5f);
                    EditorGUILayoutUtility.DrawLine();
                    GUILayout.Space(5f);
                    if (!isSampling)
                    {
                        switch (toolbarIndex)
                        {
                            case 0:
                                OnDataGUI();
                                break;
                            case 1:
                                OnRTSwitchGUI();
                                break;
                        }
                    }
                    else
                    {
                        GUILayout.FlexibleSpace();
                    }

                    GUILayout.Space(5f);
                    EditorGUILayoutUtility.DrawLine();
                    GUILayout.Space(5f);

                    using (new EditorGUI.DisabledGroupScope(isSampling))
                    {
                        if (GUILayout.Button((FrameDebugger.enabled ? "重新" : "启动FrameDebugger并") + "提取数据", GUILayout.Height(30f)))
                        {
                            if (!FrameDebugger.enabled)
                            {
                                MethodInfo EnableFrameDebugger = FrameDebuggerWindow.GetMethod("EnableFrameDebugger", BindingFlags.Instance | BindingFlags.NonPublic);
                                EnableFrameDebugger.Invoke(frameDebuggerWindow, null);
                                frameDebuggerWindow.Focus();
                                frameDebuggerWindow.Repaint();
                                Repaint();
                                //打开后需要延后一帧处理，编辑器才能反应过来
                                EditorApplication.delayCall += RefreshData;
                            }
                            else
                            {
                                Repaint();
                                RefreshData();
                            }
                        }
                    }

                    GUILayout.Space(2f);
                }
            }
        }

        /// <summary>
        /// 显示数据GUI
        /// </summary>
        private void OnDataGUI()
        {
            using (EditorGUILayout.ScrollViewScope scrollScope = new EditorGUILayout.ScrollViewScope(scrollPosition))
            {
                scrollPosition = scrollScope.scrollPosition;

                List<Shader> shaderList = eventDataDic.Keys.ToList();
                shaderList.Sort((a, b) => -string.CompareOrdinal(a.name, b.name));

                //按Shader分组
                for (int i = 0; i < shaderList.Count; i++)
                {
                    Shader shader = shaderList[i];
                    FrameDebuggerEventDataGroup dataGroup = eventDataDic[shader];
                    using (new EditorGUILayout.VerticalScope("FrameBox"))
                    {
                        using (new EditorGUILayout.HorizontalScope())
                        {
                            using (new EditorGUILayoutUtility.GUIColorScope(Color.yellow))
                            {
                                dataGroup.isFoldout = EditorGUILayout.Foldout(dataGroup.isFoldout, " " + (i + 1).ToString("00") + ". " + shader.name, true);
                            }

                            EditorGUILayout.ObjectField(shader, typeof(Shader), false, GUILayout.Width(250f));
                        }

                        using (new EditorGUILayoutUtility.VerticalScopeWithSpace(15f, 0, 8f, 3f))
                        {
                            using (new EditorGUILayout.HorizontalScope(GUI.skin.box))
                            {
                                using (new EditorGUILayoutUtility.GUIColorScope(Color.yellow))
                                {
                                    EditorGUILayout.LabelField(" Variant Count : " + dataGroup.dataDic.Count);
                                    EditorGUILayout.LabelField(" SetPass calls : " + dataGroup.setPassCalls);
                                    EditorGUILayout.LabelField(" Draw calls : " + dataGroup.drawCalls);
                                }
                            }

                            if (dataGroup.isFoldout)
                            {
                                List<string> hashList = dataGroup.dataDic.Keys.ToList();
                                hashList.Sort((a, b) => -string.CompareOrdinal(a, b));
                                //按变体分组
                                for (int j = 0; j < hashList.Count; j++)
                                {
                                    using (new EditorGUILayout.VerticalScope(GUI.skin.box))
                                    {
                                        string hashString = hashList[j];
                                        FrameDebuggerEventDataList dataList = dataGroup.dataDic[hashString];

                                        using (new GUILayout.HorizontalScope())
                                        {
                                            string passString = " " + (j + 1).ToString("00") + ". " + dataList.hashString.Split('\n')[0] +
                                                                "  [SetPass calls : " + dataList.setPassCalls +
                                                                "]  [Draw calls : " + dataList.drawCalls + "]";
                                            dataList.isFoldout = EditorGUILayout.Foldout(dataList.isFoldout, passString, true);
                                            using (new EditorGUILayoutUtility.GUIColorScope(Color.cyan))
                                            {
                                                if (GUILayout.Button("编译分析", GUILayout.Width(BUTTON_SIZE)))
                                                {
                                                    ShaderAnalysisEditorWindow.OpenWindow(dataList.keywordString);
                                                }
                                            }
                                        }

                                        using (new EditorGUILayoutUtility.VerticalScopeWithSpace(35f, 0f, 0f, 0f))
                                        {
                                            using (new EditorGUILayoutUtility.GUIColorScope(Color.cyan))
                                            {
                                                string kewords = dataList.keywordString.Split('\n')[1];
                                                EditorGUILayout.TextArea(string.IsNullOrEmpty(kewords) ? "_" : kewords, EditorStyles.wordWrappedLabel);
                                            }

                                            if (dataList.isFoldout)
                                            {
                                                GUILayout.Space(2f);
                                                EditorGUILayoutUtility.DrawLine();
                                                //FrameDebugger没开则不允许点击
                                                using (new EditorGUI.DisabledGroupScope(!FrameDebugger.enabled))
                                                {
                                                    //显示每个setpasscall
                                                    for (int k = 0; k < dataList.dataList.Count; k++)
                                                    {
                                                        ReflectionFrameDebuggerEventData data = dataList.dataList[k];
                                                        //按钮名称
                                                        bool isSelected = (int)limit.GetMethod.Invoke(null, null) == data.frameEventIndex;
                                                        using (new EditorGUILayoutUtility.GUIColorScope(isSelected ? Color.green : GUI.color))
                                                        {
                                                            if (GUILayout.Button((isSelected ? "●" : "▶") + "  Draw " + data.frameEventType + " - " + data.frameEventIndex + "   [Draw calls : " + data.drawCallCount + "]",
                                                                    EditorStyles.boldLabel, GUILayout.Height(20f)))
                                                            {
                                                                //跳转对应FrameEvent
                                                                ChangeFrameEvent(frameDebuggerWindow, data.frameEventIndex);
                                                            }
                                                        }
                                                    }
                                                }

                                                GUILayout.Space(2f);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }

                //清理RT的pass
                if (clearEventDataList.dataList.Count > 0)
                {
                    using (new EditorGUILayout.VerticalScope("FrameBox"))
                    {
                        using (new EditorGUILayoutUtility.GUIColorScope(Color.yellow))
                        {
                            clearEventDataList.isFoldout = EditorGUILayout.Foldout(clearEventDataList.isFoldout, " " + clearEventDataList.hashString, true);
                        }

                        using (new EditorGUILayoutUtility.VerticalScopeWithSpace(15f, 0, 8f, 0f))
                        {
                            using (new EditorGUILayout.HorizontalScope(GUI.skin.box))
                            {
                                using (new EditorGUILayoutUtility.GUIColorScope(Color.yellow))
                                {
                                    EditorGUILayout.LabelField(" Variant Count : " + 0);
                                    EditorGUILayout.LabelField(" SetPass calls : " + clearEventDataList.setPassCalls);
                                    EditorGUILayout.LabelField(" Draw calls : " + clearEventDataList.drawCalls);
                                }
                            }

                            if (clearEventDataList.isFoldout)
                            {
                                GUILayout.Space(2f);
                                EditorGUILayoutUtility.DrawLine();
                                //FrameDebugger没开则不允许点击
                                using (new EditorGUI.DisabledGroupScope(!FrameDebugger.enabled))
                                {
                                    using (new EditorGUILayout.VerticalScope(GUI.skin.box))
                                    {
                                        //显示每个setpasscall
                                        for (int k = 0; k < clearEventDataList.dataList.Count; k++)
                                        {
                                            ReflectionFrameDebuggerEventData data = clearEventDataList.dataList[k];
                                            //按钮名称
                                            bool isSelected = (int)limit.GetMethod.Invoke(null, null) == data.frameEventIndex;
                                            using (new EditorGUILayoutUtility.GUIColorScope(isSelected ? Color.green : GUI.color))
                                            {
                                                if (GUILayout.Button((isSelected ? "●" : "▶") + "  " + data.frameEventType + " - " + data.frameEventIndex + "   [Draw calls : " + data.drawCallCount + "]",
                                                        EditorStyles.boldLabel, GUILayout.Height(20f)))
                                                {
                                                    //跳转对应FrameEvent
                                                    ChangeFrameEvent(frameDebuggerWindow, data.frameEventIndex);
                                                }
                                            }
                                        }
                                    }

                                    GUILayout.Space(2f);
                                }
                            }
                        }
                    }
                }
            }

            GUILayout.FlexibleSpace();
        }

        /// <summary>
        /// RT切换GUI显示
        /// </summary>
        private void OnRTSwitchGUI()
        {
            double totalBandWidth = 0f;
            using (EditorGUILayout.ScrollViewScope scrollScope = new EditorGUILayout.ScrollViewScope(scrollPosition))
            {
                scrollPosition = scrollScope.scrollPosition;

                for (int i = 0; i < rtGroup.rtList.Count; i++)
                {
                    using (new GUILayout.VerticalScope(GUI.skin.box))
                    {
                        FrameDebuggerEventRtList rtList = rtGroup.rtList[i];
                        //按钮名称
                        using (new EditorGUILayout.HorizontalScope())
                        {
                            rtList.isFoldout = EditorGUILayout.Foldout(rtList.isFoldout, " " + (i + 1).ToString("00") + ". FrameEventIndex - " + rtList.frameEventIndex, true);
                            totalBandWidth += rtList.bandWidth;

                            using (new EditorGUILayoutUtility.GUIColorScope(Color.green))
                            {
                                EditorGUILayout.LabelField(rtList.bandWidthString, GUILayout.Width(100f));
                            }
                        }

                        if (rtList.isFoldout)
                        {
                            using (new EditorGUILayoutUtility.VerticalScopeWithSpace(20f, 0, 3f, 0f))
                            {
                                for (int j = 0; j < rtList.dataList.Count; j++)
                                {
                                    ReflectionFrameDebuggerEventData data = rtList.dataList[j];
                                    using (new EditorGUILayout.VerticalScope("FrameBox"))
                                    {
                                        bool isDepthRt = data.rtHasDepthTexture && j != 0 && j == rtList.dataList.Count - 1;
                                        bool isSelected = (int)limit.GetMethod.Invoke(null, null) == data.frameEventIndex;

                                        //rt索引是否一致
                                        object eventDetailsView = m_EventDetailsView.GetValue(frameDebuggerWindow);
                                        if (eventDetailsView != null)
                                        {
                                            FieldInfo m_RTIndex = FrameDebuggerEventDetailsView.GetField("m_RTIndex", BindingFlags.Instance | BindingFlags.NonPublic);
                                            isSelected &= (int)m_RTIndex.GetValue(eventDetailsView) == j;
                                        }
                                        else
                                        {
                                            isSelected = false;
                                        }

                                        using (new EditorGUI.DisabledGroupScope(!FrameDebugger.enabled))
                                        {
                                            using (new EditorGUILayoutUtility.GUIColorScope(isSelected ? Color.green : GUI.color))
                                            {
                                                string buttonString = (isSelected ? "●" : "▶") + " RtIndex - " + j;
                                                if (isDepthRt)
                                                {
                                                    buttonString += " (Depth)";
                                                }

                                                if (GUILayout.Button(buttonString, EditorStyles.boldLabel, GUILayout.Height(20f)))
                                                {
                                                    //跳转对应FrameEvent
                                                    ChangeFrameEvent(frameDebuggerWindow, data.frameEventIndex, data.rtIndex, data.rtCount, data.rtHasDepthTexture);
                                                }
                                            }
                                        }

                                        using (new EditorGUILayout.HorizontalScope())
                                        {
                                            EditorGUILayout.LabelField("Name : " + data.rtName);
                                            EditorGUILayout.LabelField("Format : " + data.formatString);
                                        }

                                        using (new EditorGUILayout.HorizontalScope())
                                        {
                                            if (data.isDepthRt)
                                            {
                                                using (new EditorGUILayoutUtility.GUIColorScope(data.rtDepthLoadAction == RenderBufferLoadAction.Load ? Color.yellow : GUI.color))
                                                {
                                                    EditorGUILayout.LabelField("DepthLoadAction : " + data.rtDepthLoadAction);
                                                }

                                                using (new EditorGUILayoutUtility.GUIColorScope(data.rtDepthStoreAction == RenderBufferStoreAction.Store ? Color.yellow : GUI.color))
                                                {
                                                    EditorGUILayout.LabelField("DepthStoreAction : " + data.rtDepthStoreAction);
                                                }
                                            }
                                            else
                                            {
                                                using (new EditorGUILayoutUtility.GUIColorScope(data.rtLoadAction == RenderBufferLoadAction.Load ? Color.yellow : GUI.color))
                                                {
                                                    EditorGUILayout.LabelField("LoadAction : " + data.rtLoadAction);
                                                }

                                                using (new EditorGUILayoutUtility.GUIColorScope(data.rtStoreAction == RenderBufferStoreAction.Store ? Color.yellow : GUI.color))
                                                {
                                                    EditorGUILayout.LabelField("StoreAction : " + data.rtStoreAction);
                                                }
                                            }
                                        }

                                        using (new EditorGUILayout.HorizontalScope())
                                        {
                                            EditorGUILayout.LabelField("Size : " + data.rtWidth + " x " + data.rtHeight);
                                            string bandWidthString = data.bandWidthString;
                                            //若深度图与第一张颜色图为同一张，不计入带宽
                                            if (isDepthRt && data.rtName == rtList.dataList[0].rtName)
                                            {
                                                bandWidthString += " (不计入)";
                                            }

                                            EditorGUILayout.LabelField("BandWidth : " + bandWidthString);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }

            GUILayout.FlexibleSpace();
            string totalBandWidthString = (totalBandWidth / (1024 * 1024 * 1024)).ToString("0.00") + " GiB/s";
            if (totalBandWidth < 1024 * 1024 * 1024)
            {
                totalBandWidthString = (totalBandWidth / (1024 * 1024)).ToString("0.00") + " MiB/s";
            }

            using (new EditorGUILayout.HorizontalScope())
            {
                EditorGUILayout.LabelField(" RT切换产生的总带宽为", GUILayout.Width(130f));
                using (new EditorGUILayoutUtility.GUIColorScope(Color.green))
                {
                    EditorGUILayout.LabelField(totalBandWidthString);
                }
            }

            EditorGUILayout.HelpBox("1. 以每秒30帧算带宽。\n2. 若深度图与目标图为同一张RT，只算一次带宽。\n3. <No name>不计入带宽\n4. 不考虑MSAA。", MessageType.Info);
        }

        /// <summary>
        /// 刷新数据
        /// </summary>
        private void RefreshData()
        {
            if (!FrameDebugger.enabled)
            {
                return;
            }

            isSampling = true;
            currentFrame = 0;
            lastFrame = 0;
            frameEventCount = (int)FrameDebuggerUtility.GetProperty("count", BindingFlags.Static | BindingFlags.Public).GetMethod.Invoke(null, null);
            currentFrameEventIndex = 1;
            needChangeFrame = true;
            currentRtIndex = 0;
            currentRtCount = 1;
            eventDataDic.Clear();
            currentRtName = "<No name>";
            rtGroup.Clear();
            clearEventDataList.hashString = "Clear Event";
            clearEventDataList.dataList.Clear();
            hasDepthRt = false;
        }

        /// <summary>
        /// 切换FrameEvent
        /// </summary>
        /// <param name="frameIndex"></param>
        /// <param name="rtIndex"></param>
        private void ChangeFrameEvent(EditorWindow frameDebuggerWindow, int frameIndex, int rtIndex = 0, int rtCount = 1, bool hasDepthRt = false)
        {
            ChangeFrameEventLimit.Invoke(frameDebuggerWindow, new object[] { frameIndex });
            RepaintOnLimitChange.Invoke(frameDebuggerWindow, null);

            object eventDetailsView = m_EventDetailsView.GetValue(frameDebuggerWindow);
            FieldInfo m_RTIndex = FrameDebuggerEventDetailsView.GetField("m_RTIndex", BindingFlags.Instance | BindingFlags.NonPublic);
            FieldInfo m_RTIndexLastSet = FrameDebuggerEventDetailsView.GetField("m_RTIndexLastSet", BindingFlags.Instance | BindingFlags.NonPublic);
            m_RTIndex.SetValue(eventDetailsView, rtIndex);
            if (rtIndex == rtCount - 1 && hasDepthRt)
            {
                rtIndex = -1;
            }

            SetRenderTargetDisplayOptions.Invoke(null, new object[] { rtIndex, Vector4.one, 0, 1 });
            m_RTIndexLastSet.SetValue(eventDetailsView, rtIndex);
            RepaintOnLimitChange.Invoke(frameDebuggerWindow, null);
            frameDebuggerWindow.Focus();
        }

        //标志位，防止读写冲突
        private bool isSampling = false;
        private int currentFrameEventIndex = 1;
        private int frameEventCount = 1;
        private int currentRtCount = 1;
        private int currentRtIndex = 0;
        private bool needChangeFrame = true;
        private string currentRtName = "<No name>";
        private bool hasDepthRt = false;
        private long currentFrame = 0;
        private long lastFrame = 0;

        /// <summary>
        /// 开启framedebugger时，会卡住主线程，这里只能用editor的update来进行间隔更新
        /// </summary>
        private void EditorUpdate()
        {
            currentFrame++;
            if (!isSampling)
            {
                return;
            }

            //CB项目这边管线定制修改过，不能马上下一帧就拿结果，这里需要每次延迟个几帧获取数据
            if (currentFrame - lastFrame <= 2)
            {
                return;
            }

            lastFrame = currentFrame;
            if (currentFrameEventIndex > frameEventCount)
            {
                //切到最后一帧
                ChangeFrameEvent(frameDebuggerWindow, frameEventCount);
                isSampling = false;
                EditorUtility.ClearProgressBar();
                Repaint();
                return;
            }

            if (EditorUtility.DisplayCancelableProgressBar("收集FrameDebugger数据", currentFrameEventIndex + "/" + frameEventCount, (float)currentFrameEventIndex / frameEventCount))
            {
                //切到最后一帧
                ChangeFrameEvent(frameDebuggerWindow, frameEventCount);
                isSampling = false;
                EditorUtility.ClearProgressBar();
                Repaint();
                return;
            }

            if (needChangeFrame)
            {
                ChangeFrameEvent(frameDebuggerWindow, currentFrameEventIndex, currentRtIndex, currentRtCount, hasDepthRt);
                //一帧设置界面变化
                needChangeFrame = false;
            }
            else
            {
                //数据是异步的，得隔一帧获取
                ReflectionFrameDebuggerEventData data = new ReflectionFrameDebuggerEventData();
                if ((bool)GetFrameEventData.Invoke(null, new object[] { currentFrameEventIndex - 1, data.data }))
                {
                    //Debug.Log("获取数据 : FrameEventIndex - " + index);
                    data.Analysis(currentRtIndex);
                    if (data.isDepthRt)
                    {
                        ReflectionFrameDebuggerEventData colorData = rtGroup.last.dataList[0];
                        if (colorData != null && colorData.rtHasDepthTexture)
                        {
                            if ((int)data.rtLoadAction == -1)
                            {
                                data.rtLoadAction = colorData.rtDepthLoadAction;
                            }

                            if ((int)data.rtStoreAction == -1)
                            {
                                data.rtStoreAction = colorData.rtDepthStoreAction;
                            }

                            if ((int)data.rtDepthLoadAction == -1)
                            {
                                data.rtDepthLoadAction = colorData.rtDepthLoadAction;
                            }

                            if ((int)data.rtDepthStoreAction == -1)
                            {
                                data.rtDepthStoreAction = colorData.rtDepthStoreAction;
                            }
                        }
                    }

                    //判定是否为ClearEvent
                    if (data.frameEventType.StartsWith("Clear"))
                    {
                        if (currentRtIndex == 0)
                        {
                            clearEventDataList.dataList.Add(data);
                        }
                    }
                    else
                    {
                        if (data.shader != null)
                        {
                            if (!eventDataDic.ContainsKey(data.shader))
                            {
                                eventDataDic.Add(data.shader, new FrameDebuggerEventDataGroup());
                            }

                            FrameDebuggerEventDataGroup dataGroup = eventDataDic[data.shader];
                            if (!dataGroup.dataDic.ContainsKey(data.hashString))
                            {
                                dataGroup.dataDic.Add(data.hashString, new FrameDebuggerEventDataList());
                                dataGroup.dataDic[data.hashString].hashString = data.hashString;
                                dataGroup.dataDic[data.hashString].keywordString = data.keywordString;
                            }

                            dataGroup.dataDic[data.hashString].dataList.Add(data);
                        }
                        else
                        {
                            Debug.Log("未知FrameEvent : " + data.frameEventIndex + "/" + frameEventCount);
                        }
                    }

                    currentRtCount = data.rtCount;
                    hasDepthRt = data.rtHasDepthTexture;
                }
                else
                {
                    Debug.LogError("获取数据失败 : FrameEventIndex - " + currentFrameEventIndex + "/" + frameEventCount);
                    isSampling = false;
                    EditorUtility.ClearProgressBar();
                    return;
                }

                //Debug.Log("FrameEventIndex - " + frameEventIndex + " ; " + "currentRtIndex - " + currentRtIndex + " ; " + data.rtName);
                //记录RT切换的pass
                if (currentRtIndex == 0 && data.rtName != currentRtName)
                {
                    currentRtName = data.rtName;
                    //添加一个
                    rtGroup.rtList.Add(new FrameDebuggerEventRtList());
                    rtGroup.last.frameEventIndex = currentFrameEventIndex;
                }
                else
                {
                    //不在切换rt的pass内，直接把index跳到最后
                    currentRtIndex = currentRtCount - 1;
                }

                //往后的在这里插入即可
                if (rtGroup.last != null && rtGroup.last.frameEventIndex == currentFrameEventIndex)
                {
                    rtGroup.last.dataList.Add(data);
                }

                //rt自增
                currentRtIndex++;
                if (currentRtIndex == currentRtCount)
                {
                    currentRtIndex = 0;
                    currentFrameEventIndex++;
                }

                needChangeFrame = true;
            }
        }
    }
}